from datetime import datetime
from django.views.decorators.csrf import csrf_exempt
from core.enum import RESPONSE_SUCCESS, RESPONSE_ERROR
from ..models import Comment
from core.decorators import render

METHOD_INCREASE = 0
METHOD_DECREASE = 1

@csrf_exempt
@render(type="json")
def action(request):

    try:
        method = int(request.POST.get("method", METHOD_INCREASE))
        cid = int(request.POST.get("cid"))

        request.session.set_expiry(datetime(2029, 12, 1, 0, 0, 0))
        if not request.session.get('comments_rating_votes', None):
            request.session['comments_rating_votes'] = []

        if cid in request.session['comments_rating_votes']:
            raise Exception("Already voted")

        if cid:
            comment = Comment.objects.get(pk=cid)
            if method == METHOD_INCREASE:
                comment.rating += 1
                comment.user.get_profile().rating += 1

            if method == METHOD_DECREASE:
                comment.rating -= 1
                comment.user.get_profile().rating -= 1

            comment.save()
            comment.user.get_profile().save()


            request.session['comments_rating_votes'].append(cid)

            return {
                'code': RESPONSE_SUCCESS,
                'rating': comment.rating
            }

    except Exception, e:
        pass

    return {
        'code': RESPONSE_ERROR
    }